<?php
/**
 * 微信公众号开发整合类.
 * User: 1874
 * Date: 2018/8/8
 * Time: 20:46
 */

namespace app\common\controller;
use think\facade\Config;

class Wechat {
	//公众平台请求开发者时需要
    protected $web_url; //网址
	protected $token;  //开发配置token
	protected $app_id;  //公众号appId
	protected $secret; //公众号secret
	protected $mch_id;  //商户号id
	protected $apiKey; //商户号API秘钥
	protected $apiclient_key; //商户apiclient_key证书
	protected $apiclient_cert; //商户apiclient_cert证书
	/**
     * 定义一个构造方法初始化赋值
     */
	public function __construct(){
	    //获取平台配置
        $config = Config::get("app.wechat_config");
        //赋值
		$this->token = $config['token'];
        $this->app_id = $config['app_id'];
        $this->secret = $config['app_secret'];
        $this->web_url = $config['app_url'];
        $this->mch_id = $config['mch_id'];
        $this->apiKey = $config['api_key'];
        $this->apiclient_key = $config['apiclient_key'];
        $this->apiclient_cert = $config['apiclient_cert'];
	}
	//文本XML模板
	private $textTpl = "<xml>  
							<ToUserName><![CDATA[%s]]></ToUserName>  
							<FromUserName><![CDATA[%s]]></FromUserName>  
							<CreateTime>%s</CreateTime>  
							<MsgType><![CDATA[text]]></MsgType>  
							<Content><![CDATA[%s]]></Content>  
                        </xml>"; 
	//图片XML模板
	private $imgTpl = "<xml>
							 <ToUserName><![CDATA[%s]]></ToUserName>
							 <FromUserName><![CDATA[%s]]></FromUserName>
							 <CreateTime>%s</CreateTime>
							 <MsgType><![CDATA[image]]></MsgType>
							 <Image>
								<MediaId><![CDATA[%s]]></MediaId>
							 </Image>
					   </xml>"; 
	//图文XML模板
	private $newTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[news]]></MsgType>
							<ArticleCount>%s</ArticleCount>
							<Articles>%s</Articles>
					   </xml>";
	//某个图文模板<Articles>中间部分
	private $itemTpl = '<item>
							<Title><![CDATA[%s]]></Title>
							<Description><![CDATA[%s]]></Description>
							<PicUrl><![CDATA[%s]]></PicUrl>
							<Url><![CDATA[%s]]></Url>
						</item>';
	/*
	 * 公众号响应消息交互
	 * $postObj->FromUserName; 获取用户openid
	 * $postObj->ToUserName;	获取开发者微信号
	 */
	public function responseMsg(){
		//获取微信POST xml数据包 < php7.0
		//$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		//获取微信POST xml数据包 > php7.0
		$postStr = file_get_contents("php://input");
		//libxml_disable_entity_loader是防止XML外部实体注入，最好的方法是检查XML的有效性
		libxml_disable_entity_loader(true);
		//处理POST xml数据包
		$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
		//回复类型
		$msgType = $postObj->MsgType;	
		//根据输入值回复类型
		switch($msgType){
			case 'event':
				//判断具体的事件类型（关注、取消、点击）
				$event = $postObj->Event;
				if($event == 'subscribe') { // 关注事件
					$this->doSubscribe($postObj);
				}elseif($event == 'unsubscribe'){
					$this->doUnsubscribe($postObj); // 取消关注事件
				}elseif ($event == 'CLICK') {//菜单点击事件
					$this->doClick($postObj);
				}elseif ($event == 'VIEW') {//菜单连接跳转事件
                    exit('菜单连接跳转事件');
					//$this->doView($postObj);
				}
				break;
			case 'text':
				//处理文本消息方法
				$this->doText($postObj);
				break;
			case 'image':
				//处理图片消息方法
				$this->doImg($postObj,$postObj->MediaId);
				break;
		}
		//根据输入值回复不用信息	
		/**/
			
	} 
	/**
	 * 处理取消关注事件
	 */
	private function doUnsubscribe($postObj){
		echo '取消关注';
	}
	/**
	 * 处理该关注事件，向用户发送关注信息
	 */
	private function doSubscribe($postObj){
		$content = array(
			array(
				'title'=>'感谢您关注本公众平台！',
				'description' => '为您准备了小礼物，请点击查收',
				'picurl'=>'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508995172738&di=4d5156eba68eda6922f7b8df4cbbffa4&imgtype=0&src=http%3A%2F%2Fd.yymoban.com%2Fuploads%2Fallimg%2F1612%2F1-16122910562I51.gif',
				'url'=>'http://c.eqxiu.com/s/wBScwOAC',
			)
		);
		$this->doNew($postObj,$content);
	}
	/**
	 * 点击自定义菜单触发事件
	 */
	private function doClick($postObj) {
		$fromUsername = $postObj->FromUserName; //获取用户openid
		$toUsername = $postObj->ToUserName;	//获取开发者微信号
		$contentStr = '你点击了菜单，携带的KEY为: ' . $postObj->EventKey;
		$this->msgText($fromUsername,$toUsername,$contentStr);
	}
	/**
	 * 处理文本信息
	 * $this->Transformation 编码转换
	 */
	private function doText($postObj) {
		$fromUsername = $postObj->FromUserName; //获取用户openid
		$toUsername = $postObj->ToUserName;	//获取开发者微信号
		$keyword = trim($postObj->Content);	//获取文本消息

		switch($keyword){
			case 'openid':
				$contentStr = $fromUsername;
				$this->msgText($fromUsername,$toUsername,$contentStr);
				break;
			case '英雄联盟':
				$contentStr = array(
					array(
						'title'=>'无形之刃，最为致命',
						'description' => '吾所成之事，不可逆也',
						'picurl'=>'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509585181&di=cf4e0c27108853e1ced18b26701fc99d&imgtype=jpg&er=1&src=http%3A%2F%2Fpic2.52pk.com%2Ffiles%2F170216%2F7427446_155652_1.jpg',
						'url'=>'https://tieba.baidu.com/f?ie=utf-8&kw=%E5%BD%B1%E6%B5%81%E4%B9%8B%E4%B8%BB&fr=search',
					),
					array(
						'title'=>'死亡如风，常伴吾身',
						'description' => '哈撒给，面对疾风吧',
						'picurl'=>'http://i2.hdslb.com/bfs/archive/30603df7288c8351e0b8a9eee6706c3f931df00b.jpg',
						'url'=>'https://tieba.baidu.com/f?ie=utf-8&kw=%E7%96%BE%E9%A3%8E%E5%89%91%E8%B1%AA',
					),
					array(
						'title'=>'一轮新月，正在冉冉升起',
						'description' => '我是月亮的选择',
						'picurl'=>'http://i1.hdslb.com/bfs/archive/46282d1b998e8bcf00b93b64b2bbd3345b050753.jpg',
						'url'=>'https://tieba.baidu.com/f?ie=utf-8&kw=%E7%9A%8E%E6%9C%88%E5%A5%B3%E7%A5%9E',
					),
				);
				$this->doNew($postObj,$contentStr);
				break;
			case '看电视':
				$contentStr = '<a href="www.goudaitv.com">狗带TV</a>';
				$this->msgText($fromUsername,$toUsername,$contentStr);
				break;
			case '达康书记':
				$mediaId = 'DCi7EA8S12Zq2BcKjbxAwujedGiGJ_FyW-uvPlrPjb89CUE6cKXYls3JP8sBhyUS';
				$this->doImg($postObj,$mediaId);
				break;
			default:
				//接入图灵机器人
				$url = 'http://www.tuling123.com/openapi/api?key=9a8969fd1250417eb53106566b189d3f&info='.$keyword;
				$json = $this->curl_get($url); 
				$arr = json_decode($json, true);
				$contentStr = $arr['text'];
				$this->msgText($fromUsername,$toUsername,$contentStr);
				break;
		}
	}
	/**
	 * 处理图片消息
	 */
	private function doImg($postObj,$mediaId) {
		$fromUsername = $postObj->FromUserName; //获取用户openid
		$toUsername = $postObj->ToUserName;	//获取开发者微信号
		
		//$mediaId = $postObj->MediaId;
		//$this->msgText($fromUsername,$toUsername,$time,$mediaId); //反向获取接收图片的mediaId
		//回复图片消息
		$this->msgImg($fromUsername,$toUsername,$mediaId);
	}
	/**
	 * 处理图文消息
	 */
	private function doNew($postObj,$contentStr) {
		$fromUsername = $postObj->FromUserName; //获取用户openid
		$toUsername = $postObj->ToUserName;	//获取开发者微信号
		$this->msgNew($fromUsername,$toUsername,$contentStr); //回复图文消息
	}
	/**
	 * 回复文本信息
	 * @param  [type] $toUsername     目标用户ID
	 * @param  [type] $fromUsername   来源用户ID
	 * @param  [type] $contentStr 	内容
	 * @param  [type] time() 	时间
	 */
	private function msgText($fromUsername,$toUsername,$contentStr) {
		$response = sprintf($this->textTpl, $fromUsername, $toUsername,time(),$contentStr);
		die($response);
	}
	/**
	 * 回复图片信息
	 * @param  [type] $toUsername     目标用户ID
	 * @param  [type] $fromUsername   来源用户ID
	 * @param  [type] $contentStr 	内容
	 * @param  [type] time() 	时间
	 * @param  [type] $mediaId 	图片消息媒体id
	 */
	private function msgImg($fromUsername,$toUsername,$mediaId) {
		$response = sprintf($this->imgTpl, $fromUsername, $toUsername,time(),$mediaId);
		die($response);
	}
	/**
	 * 回复图文信息
	 * @param  [type] $toUsername     目标用户ID
	 * @param  [type] $fromUsername   来源用户ID
	 * @param  [type] $contentStr 	内容
	 * @param  [type] time() 	时间
	 * @param  [type] $itemArry <item>中图文内容
	 * @param  [type] count($contentStr) 图文个数
	 */
	private function msgNew($fromUsername,$toUsername,$contentStr=array()) {
		//拼凑文章<item>部分
		$itemArry = '';
		foreach ($contentStr as $value) {
			$itemArry .= sprintf($this->itemTpl,$value['title'],$value['description'],$value['picurl'],$value['url']);
		}
		//拼凑主体<Articles>部分
		$response = sprintf($this->newTpl, $fromUsername, $toUsername,time(),count($contentStr),$itemArry);
		die($response);
	}

//===========================================================服务器配置效验token============================================================
	/*
	 * 效验签名合法性
	 */
	public function valid(){
		$echostr = $_GET["echostr"];	//随机字符串
		if($this->checkSignature()){
			echo $echostr;
			exit;
		}else{
			echo 'error';
			exit;
		}
	}
	/*
	 * 验证消息的确来自微信服务器，检验微信加密签名是否有效
	 */
	public function checkSignature(){
		//接收微信服务器get请求过来的4个参数
		$signature = $_GET["signature"]; //微信加密签名
		$timestamp = $_GET["timestamp"]; //时间戳
		$nonce =  $_GET["nonce"];		//随机数
		$token = $this->token; //填写的TOKEN
		//将TOKEN、timestamp、nonce进行字典序列排序
		$tmpArr = array($token,$timestamp,$nonce);
		sort($tmpArr,SORT_STRING);
		//将三个字符串拼接成一个字符串进行sha1加密
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpArr);
		//将加密后的字符串和signature对比
		if($tmpStr == $signature){
			return true;
		}else{
			return false;
		}
	}
//===================================================================微信接口调用===================================================================
	/*
	 * 获取唯一凭证access_token
	 */
	public function getAccessToken(){
		//获取access_token 
		$accessToken = $this->curl_get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->app_id.'&secret='.$this->secret.'');
		$result = json_decode($accessToken, true);
		$token = $result['access_token'];
		
		return $token;
	}
	/*
	 * 通过URL 重定向获取code
	 * @param  [type] $url 将要跳转的地址
	 * @param  [type] $stype 选择重定向方式
	 */
	public function getCode($url,$type){
		$redirectUrl = urlencode($url);

		switch($type){
			case 1:
				//可以获取更多的用户资料
				$scope = 'snsapi_userinfo';
				break;
			case 2:
				//只能获取access_token和openID
				$scope = 'snsapi_base';
				break;
		}
		$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->app_id.'&redirect_uri='.$redirectUrl.'&response_type=code&scope='.$scope.'&state=STATE#wechat_redirect';
		header("Location:".$url);
	}
	/**
	 * 通过code获取临时凭证access_token
	 * @param string $code code值
	 * @param int $type 1=公众号，2=小程序
     * @return array
	 */
	public function getTemporaryAccessToken(string $code, int $type){
	    if($type == 1){
            $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->app_id.'&secret='.$this->secret.'&code='.$code.'&grant_type=authorization_code';
        }else{
            $get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->app_id.'&secret='.$this->secret.'&js_code='.$code.'&grant_type=authorization_code';
        }
		//请求 $get_token_url 地址获得 json 格式信息
		$json = $this->curl_get($get_token_url); 
		//解密json获得数组
		$array = json_decode($json, true);
		return $array;
	}
    /*
     * 临时凭证access_token获取授权后用户资料
     */
    public function getOauthUserInfo($token, $openid){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid.'&lang=zh_CN';
        $json = $this->curl_get($url); //获取微信用户基本信息
        $user_data = json_decode($json, true);

        return $user_data;
    }
	/*
	 * 唯一凭证access_token获取用户详细资料
	 */
	public function getUserInfo($access_token, $openid){
		//获取用户详细信息
		$userdata = $this->curl_get('https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN');
		$array = json_decode($userdata,true);
		
		return $array;
	}
	/*
	 * 批量获取关注用户列表
	 * @param unknown $next_openid 最后一个openid
	 */
	public function getUserList($access_token,$next_openid=''){
		$result = $this->curl_get('https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token.'&next_openid='.$next_openid.'');
		$json = json_decode($result,true);
		
		return $json;
	}
	/*
	 * 唯一凭证access_token，获取jsapi_ticket签名凭证
	 */
	public function getJsApiTicket($access_token){
		$ticketJson = $this->curl_post("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi");
		$ticketArr = json_decode($ticketJson);
		//得到jsapi_ticket，有效时间7200秒,建议缓存起来
		$ticketStr = $ticketArr->ticket;
		
		return $ticketStr;
	}
	/*
	 * 获得jsapi_ticket之后，生成JS-SDK权限验证的签名了。
	 * @param unknown $ticketStr jsapi_ticket生成签名的凭证
	 */
	public function getSignature($ticketStr){
		$str = "jsapi_ticket=".$ticketStr."&noncestr=9hKgyCLgGZOgQmEI&timestamp=1421142450&url=".$this->web_url.$_SERVER["REQUEST_URI"];
        $signature = sha1($str);
		
		return $signature;
	}
	/*
	 * 唯一凭证access_token,发送模板消息
	 * @param  [type] $template 模板
	 */
	public function templateMessage($accessToken,$template){
		//获取服务器时间
		date_default_timezone_set("Asia/Shanghai");
		//模板消息
		/*$template = array(
				'touser'=>'oprWAs4tFh-zLbNu6Om1z8IAWbYw', //发送给某用户openid
				'template_id'=>"-91Xb0ZbEJKg36tc9J4Ce7hph8GZqJleA7c2x9eMQkM", //模板ID
				'url'=>"http://www.baidu.com",
				'topcolor'=>"#7B68EE",
				'data'=>array(
						'first'=>array('value'=>urlencode("您好,1874"),'color'=>"#FF0000"),
						'time'=>array('value'=>urlencode(date("Y-m-d H:i:s")),'color'=>'#FF0000'),
						'cost'=>array('value'=>urlencode('这是测试'),'color'=>'#FF0000'),
						'dispalyCount'=>array('value'=>urlencode('这是测试'),'color'=>'#FF0000'),
						'clickCount'=>array('value'=>urlencode('这是测试'),'color'=>'#FF0000'),
						'clickRate'=>array('value'=>urlencode('这是测试'),'color'=>'#FF0000'), 
						'remark'=>array('value'=>urlencode('这是测试'),'color'=>'#FF0000'), 
					)
				);*/
		//将模板消息打包成json
		$json_template = json_encode($template);
		//请求模板发送接口地址
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;
		$res = $this->curl_post($url,urldecode($json_template));
		
		/*快速发送，无返回值，适合发送量较大情况*/
		/*$params = json_encode($template, JSON_UNESCAPED_UNICODE);
        $file = fsockopen('api.weixin.qq.com', 80, $error, $errstr, 1);
        $http = "POST /cgi-bin/message/template/send?access_token={$accessToken} HTTP/1.1\r\nHost: api.weixin.qq.com\r\nContent-type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($params)."\r\nConnection:close\r\n\r\n$params\r\n\r\n";
        fwrite($file, $http);
        fclose($file);*/

		if ($res['errcode'] == '0') {
			return true;
		}else{
			return false;
		}
	}
	/*
	 * 唯一凭证access_token,发送设置自定义菜单
	 * @param  [type] $jsonmenu 菜单设置内容
	 */
	public function customMenu($access_token,$jsonmenu=null){
		/*$jsonmenu = '{
			 "button":[
			 {    
				  "type":"click",
				  "name":"今日歌曲",
				  "key":"V1001_TODAY_MUSIC"
			  },
			  {
				   "name":"菜单",
				   "sub_button":[
				   {    
					   "type":"view",
					   "name":"搜索",
					   "url":"http://www.baidu.com"
					},
					{
					   "type":"view",
					   "name":"视频",
					   "url":"http://v.qq.com/"
					},
					{
					   "type":"click",
					   "name":"赞一下我们",
					   "key":"V1001_GOOD"
					}]
			   }
			]
		 }';*/
		$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
		$json = $this->curl_post($url, $jsonmenu); 
		$result = json_decode($json, true);
		if($result['errcode'] == '0' && $result['errmsg'] == 'ok'){
			return true;
		}else{
			return false;
		}
	}
	/*
	 * 唯一凭证access_token,上传永久图片素材
	 * @param  [type] $file_info 图片内容数组
	 */
	public function add_material_image($access_token,$file_info){
		/*
		$file_info = array(
			'filename' => dirname( __FILE__ )."/0.jpg";, 
			'content-type' => 'image/jpg', //文件类型
			'filelength' => '15' //图文大小
        );*/
		
        $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$access_token."&type=image";
        $data = array("media" => "@".$file_info['filename'], 'form-data' => $file_info);
		$json = $this->curl_post($url,$data); 
	
        $result = json_decode($json, true);
        if($result['media_id']){
			return true;
		}else{
			return false;
		} 

	}
	/*
	 * 唯一凭证access_token,上传卡卷logo
	 * @param  [type] $imgurl logo地址
	 * @param  [type] $$result 返回logo地址
	 */
	public function upload_card_logo($access_token,$imgurl){
		$data = array("buffer" => "@".$imgurl);	
		$url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$access_token;
		
		$json = $this->curl_post($url,$data); 
		$result = json_decode($json, true);
		
		return $result;
	}
	/*
	 * 唯一凭证access_token,创建卡卷,需要JSON格式数据
	 */
	public function create_card(){
		$access_token = "6xaOU662BM_MeipE59xQdPeIJ945COAjF9F6TssaHr2RLtfOrpdzPSlzxZP1RpYRP9riUEZHQHfCv2OZvtT8x4mAwwc3m_f_ch81iWmcpvPP2RsHqbqOaP75PVin-v01UJKjABAJYZ";
		
		$data = '{
		  "card": {
			  "card_type": "GROUPON",
			  "groupon": {
				  "base_info": {
					  "logo_url":  "http://mmbiz.qpic.cn/mmbiz_jpg/rTIBGP1ID6w4DjkvHTEypvFGBPqfQyic9Y4TK3d4haoOrTR7ZBnUODK5E0rFIaBiagHdHZt7FFGIFIhEPsShs0Wg/0",
					  "brand_name": "微信餐厅",
					  "code_type": "CODE_TYPE_TEXT",
					  "title": "132元双人火锅套餐",
					  "color": "Color010",
					  "notice": "使用时向服务员出示此券",
					  "service_phone": "020-88888888",
					  "description": "不可与其他优惠同享\n如需团购券发票，请在消费时向商户提出\n店内均可使用，仅限堂食",
					  "date_info": {
						  "type": "DATE_TYPE_FIX_TIME_RANGE",
						  "begin_timestamp": 1397577600,
						  "end_timestamp": 1472724261
					  },
					  "sku": {
						  "quantity": 500000
					  },
					  "use_limit":100,
					  "get_limit": 3,
					  "use_custom_code": false,
					  "bind_openid": false,
					  "can_share": true,
					  "can_give_friend": true,
					  "location_id_list": [
						  123,
						  12321,
						  345345
					  ],
					  "center_title": "顶部居中按钮",
					  "center_sub_title": "按钮下方的wording",
					  "center_url": "www.qq.com",
					  "custom_url_name": "立即使用",
					  "custom_url": "http://www.qq.com",
					  "custom_url_sub_title": "6个汉字tips",
					  "promotion_url_name": "更多优惠",
					  "promotion_url": "http://www.qq.com",
					  "source": "大众点评"
				  },
				   "advanced_info": {
					   "use_condition": {
						   "accept_category": "鞋类",
						   "reject_category": "阿迪达斯",
						   "can_use_with_other_discount": true
					   },
					   "abstract": {
						   "abstract": "微信餐厅推出多种新季菜品，期待您的光临",
						   "icon_url_list": [
							   "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sj  piby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0"
						   ]
					   },
					   "text_image_list": [
						   {
							   "image_url": "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sjpiby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0",
							   "text": "此菜品精选食材，以独特的烹饪方法，最大程度地刺激食 客的味蕾"
						   },
						   {
							   "image_url": "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sj piby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0",
							   "text": "此菜品迎合大众口味，老少皆宜，营养均衡"
						   }
					   ],
					   "time_limit": [
						   {
							   "type": "MONDAY",
							   "begin_hour":0,
							   "end_hour":10,
							   "begin_minute":10,
							   "end_minute":59
						   },
						   {
							   "type": "HOLIDAY"
						   }
					   ],
					   "business_service": [
						   "BIZ_SERVICE_FREE_WIFI",
						   "BIZ_SERVICE_WITH_PET",
						   "BIZ_SERVICE_FREE_PARK",
						   "BIZ_SERVICE_DELIVER"
					   ]
				   },
				  "deal_detail": "以下锅底2选1（有菌王锅、麻辣锅、大骨锅、番茄锅、清补 凉锅、酸菜鱼锅可选）：\n大锅1份 12元\n小锅2份 16元 "
			  }
		  }
		} ';
		
		$url = "https://api.weixin.qq.com/card/create?access_token=".$access_token;
		
		$json = $this->curl_post($url,$data); 
		$result = json_decode($json, true);
		
		echo '<pre>';
		print_r($result);		
	}
    /**
     * 退款
     * @param float $totalFee 订单金额 单位元
     * @param float $refundFee 退款金额 单位元
     * @param string $refundNo 退款单号
     * @param string $wxOrderNo 微信订单号 (商户订单号与微信订单号二选一，至少填一个)
     * @param string $orderNo 商户订单号 (商户订单号与微信订单号二选一，至少填一个)
     * @param string $refundDesc 退款原因
     * @return string
     */
    public function doRefund($totalFee, $refundFee, $refundNo, $wxOrderNo='',$orderNo='', $refundDesc='') {
        //所需数据
        $data = [
            'appid' => $this->app_id, //公众号appId
            'mch_id' => $this->mch_id, //商户号id
            'nonce_str' => $this->createNonceStr(), //生成随机字符串
            'total_fee' => intval($totalFee * 100), //订单金额  单位 转为分
            'refund_fee' => intval($refundFee * 100), //退款金额 单位 转为分
            'sign_type' => 'MD5', //签名类型 支持HMAC-SHA256和MD5，默认为MD5
            'transaction_id' => $wxOrderNo, //微信订单号
            'out_trade_no' => $orderNo, //商户订单号
            'out_refund_no' => $refundNo, //商户退款单号
            'refund_desc' => $refundDesc, //退款原因（选填）
        ];
        //生成签名
        $data['sign'] = $this->getRefundSign($data, $this->apiKey);
        //发送xml数据
        $responseXml = $this->weChatRefundCurlPost('https://api.mch.weixin.qq.com/secapi/pay/refund', self::arrayToXml($data));
        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if($unifiedOrder === false) {
            //payLogAdd('微信订单号：'.$wxOrderNo.'，微信退款xml解析错误');
        }
        if($unifiedOrder->return_code != 'SUCCESS') {
            $error = ['info'=>'微信订单号：'.$wxOrderNo,'error'=>$unifiedOrder->return_msg,'status'=>0];
            //payLogAdd(json_encode($error,JSON_UNESCAPED_UNICODE));
        }
        if($unifiedOrder->result_code != 'SUCCESS') {
            $error = ['info'=>'微信订单号：'.$wxOrderNo,'error'=>$unifiedOrder->err_code_des,'status'=>0];
            //payLogAdd(json_encode($error,JSON_UNESCAPED_UNICODE));
        }
        if(empty($error)) $error = ['info'=>'退款成功','status'=>1];

        return $error;
    }
    /*
     * 组成微信需要XML数据
     */
    public static function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
    /*
     * 生成随机字符串方法
     */
    protected function createNonceStr($length = 32){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ( $i = 0; $i < $length; $i++ ) {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    /*
     * 生成退款使用签名
     */
    protected static function getRefundSign($params, $key) {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));

        return $signStr;
    }
    /*
     * 将退款需要的信息组成签名算法
     */
    protected static function formatQueryParaMap($paraMap, $urlEncode = false) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }

        return $reqPar;
    }
    /*
	 * 微信退款使用curl post方法
	 */
    protected function weChatRefundCurlPost($url = '', $postData = '', $options = array()) {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        //apiclient_cert证书绝对路径
        curl_setopt($ch, CURLOPT_SSLCERT, $this->apiclient_cert);
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        //apiclient_key证书绝对路径
        curl_setopt($ch, CURLOPT_SSLKEY, $this->apiclient_key);
        //第二种方式，两个文件合成一个.pem文件
        //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "curl出错，错误码: ".$error."<br>";
            curl_close($ch);
            return false;
        }
    }
	/*
	 * curl发送get请求方法
	 * curl_init(); 初始化
	 * curl_setopt(); 传输设置
	 * curl_exec(); 获取结果
	 * curl_close(); 关闭curl
	 */
	public function curl_get($url=null){ 
		$ch = curl_init(); //初始化curl
		$timeout = 120;  //120秒未响应中断连接
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //屏蔽https检测
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);//获取页面内容，不直接输出到页面 设置参数：1 或 true
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //请求响应时间
		$file_contents = curl_exec($ch);
		curl_close($ch); 
		return $file_contents;
	}
	/*
	 * curl发送 POST请求数据
	 */
	public function curl_post($url,$data=array()){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		if(!empty($data)){
			//PHP5.4以上，上传永久图片素材必加
			curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
			// POST数据
			curl_setopt($ch, CURLOPT_POST, 1);
			// 把post的变量加上
			@curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}
	/**
	 * 转换编码格式
	 */
	private function Transformation($string){
		//iconv函数库能够完成各种字符集间的转换
		$contentStr = iconv('gb2312', 'UTF-8//IGNORE', $string);
		return $contentStr;
	}
}

?>